#coding:utf-8
from pytube import YouTube  
import time
import os
import re

targetPath=r'F:/filedata/'

def mymkdir(filepath):
    #print(type(filepath))
    filepath = filepath.strip()
    filepath = filepath.rstrip("\\")
    isExists = os.path.exists(filepath)
    if isExists:
        #print(filepath + ' 目录已存在')
        return False
    else:
        os.makedirs(filepath)
        print('创建成功')
        return True
    
def download_video(path):
    timepath=time.strftime('%Y/%m/%d/')
    timepath=targetPath+timepath+'video/youtube/'
    mymkdir(timepath)
    print('视频预存地址',timepath)
    video_url = 'https://www.youtube.com/watch?v=iocJc342Q8s'   
    if len(path) != 0:
        video_url=path
    try:
        #yt = YouTube(video_url)  
        #使用代理
        #yt = YouTube(video_url)  
        yt = YouTube(video_url,proxies={'https': '127.0.0.1:7890'})  


        print(yt.title)           # 影片標題
        #print(yt.length)          # 影片長度 ( 秒 )
        print(yt.length/60)          # 影片長度 ( 分 )
        #print(yt.author)          # 影片作者
        #print(yt.channel_url)     # 影片作者頻道網址
        #print(yt.thumbnail_url)   # 影片縮圖網址
        #print(yt.views)           # 影片觀看數
        #video = yt.streams.first()  
        #timepath='./video/'

        video=yt.streams.filter().get_highest_resolution()

        title=re.sub(' |/|-|\W|[\/:|?*"<>]','',yt.title)
        filename=timepath+title+'.mp4'
        print('下载中',filename)
        video.download(filename=filename) 
        print('下载成功')
    except Exception as e:
        print('下载失败',e)
        return False
    return True

if __name__=='__main__':
    with open(r'./youtubeurls.txt','r') as fp:
        for item in fp:
            print('text=',item)
            num=0
            while True:
                status=download_video(item)
                if status:
                    break
                if num>50:
                   break
                num=num+1

    print('结束')
